package com.zking.myservlet.product;

import com.zking.dao.CategoryDao;
import com.zking.dao.ProductDao;
import com.zking.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;


@MultipartConfig(
        maxFileSize = 1024 * 1024 * 5,   // 最大上传文件的大小
        maxRequestSize = 1024 * 1024 * 10 // 请求的总最大大小
)
@WebServlet("/manage/ProductAdd")
public class ProductAdd extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String name = req.getParameter("productName");
        String description = req.getParameter("productDescription");
        int childId = Integer.parseInt(req.getParameter("childId"));
        int parentId = CategoryDao.getBigCategoryIdByChildId(childId);
        double price = Double.parseDouble(req.getParameter("productPrice"));
        int count = Integer.parseInt(req.getParameter("productStock"));
        Part imagePart = req.getPart("productFileName");
        InputStream imageContent = null;
        if(imagePart!=null)
        {
            imageContent = imagePart.getInputStream();
            boolean flag = ProductDao.addProduct(
                    new Product(name, description, parentId, childId, null, price, count, imageContent));
            if(flag){
                resp.sendRedirect("manage-result.jsp");
            }
        }
    }
}
